package com.cxs.controller;

import com.cxs.dto.LoginUserDTO;
import cxs.utils.utils.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AccountException;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;

/*
 * @Author:cxs
 * @Date:2021/10/14  19:08
 * @Version 1.0
 * @Motto:放下杂念,只为迎接明天更好的自己
 * */
@RestController
@RequestMapping("/auth")
@Slf4j
@CrossOrigin(allowCredentials = "true")
public class AuthController {

    @PostMapping("/login")
    public Result login(@RequestBody @Valid LoginUserDTO user, BindingResult result){
        if(result.hasErrors()){
            return Result.OK(result.getFieldError().getDefaultMessage(),203,null);
        }
        Subject subject = SecurityUtils.getSubject();

        try {
            subject.login(new UsernamePasswordToken(user.getUsername(), user.getPassword()));
        } catch (UnknownAccountException e) {
            log.error("username is not exists");
            return Result.failare("用户名不存在");
        } catch (AccountException ue){
            log.error("username is null");
            return Result.failare(ue.getMessage());
        } catch (IncorrectCredentialsException pe){
            log.error("password错误");
            return Result.failare("密码输入有误");
        }
        System.out.println(subject.getPrincipal());
        return Result.OK("登录成功",200,subject.getPrincipal());
    }

    @GetMapping("/logOut")
    public Result logOut(){
        Subject subject = SecurityUtils.getSubject();

        subject.logout();

        return Result.OK("OK");
    }
}
